<script type="text/javascript">
    const fileInputDom = document.querySelector("input[type=file]");
    
    fileInputDom.addEventListener("change", function(event) {
        // 服务器端发送添加图片请求
        let files = event.target.files;
        let albumName = document.querySelector(".selected").dataset.name;

        for (let i = 0; i < files.length; i++) {
            let formdata = new FormData();
            formdata.append("myFile", files[i]);

            fetch(`/upload-pic/${albumName}`, {
                method: "post",
                // headers: {
                //   "Content-Type": "multipart/form-data"
                // },
                body: formdata
            }).then(function(res) {
                // res instanceof Response == true.
                if (res.ok) {
                    res.json().then(function(data) {
                        let revisedUrl = `/img/${albumName}/${data.filename}`;
                        addDiv(revisedUrl);
                    });
                } else {
                    console.log("Looks like the response wasn't perfect, got status", res.status);
                }
            }, function(e) {
                console.log("Fetch failed!", e);
            });
        }
        
    });
        
    function setDivPositionInPage(div, parentNode, pageIndex) {
        const total = 15;
        let tempStyle = div.style; 

        let len = parentNode.children.length;
        if (len >= (pageIndex - 1) * total && len < pageIndex * total) {
            tempStyle.display = "inline-block";
        } else {
            tempStyle.display = "none";    
        }
    }
    function addDiv(url) {
        var img = new Image();
        img.src = url;

        var button = document.createElement("div");
        button.classList.add("delete");
        button.innerHTML = "X";

        var div = document.createElement("div");
        div.classList.add("img");
        // div.style.position = "relative";

        div.appendChild(img);
        div.appendChild(button);

        const parentNode = document.querySelector(".selected");
        const spandom = document.querySelector("nav>span[data-is-clicked=true]");            
        // set the Div style
        setDivPositionInPage(div, parentNode, spandom.innerText);

        parentNode.appendChild(div);
    }
</script>